package com.xjj.servicejob.controller.admin;

import com.xjj.entity.Advice;
import com.xjj.entity.ResponseEntity;
import com.xjj.util.utils.OssManagerUtil;
import com.xjj.util.utils.RandomUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author sjy
 * @create 2022-10-20 11:34
 * 上传文件和图片
 */
@RestController
public class UploadController {
    @RequestMapping("/job/admin/upload")
    public ResponseEntity uploadImg(MultipartFile file) throws IOException {
         if (file == null || file.isEmpty()) {
            return ResponseEntity.FAIL("文件找不到", null);
        }
        // 获取图片后缀
        String submittedFileName = file.getOriginalFilename();
        String suffix = submittedFileName.substring(submittedFileName.lastIndexOf("."));
        // 图片随机前缀
        String fileName = RandomUtil.getImgRandom();
        // 拼接文件名
        String url = OssManagerUtil.uploadImage(fileName + suffix, file.getSize(), file.getInputStream());
        return ResponseEntity.SUCCESS("上传成功", url);
    }

    /**
     * 文件下载
     * @param advice
     * @param response
     * @return
     */
    @PostMapping("/job/admin/downLoadFile")
    public ResponseEntity downloadFile(@RequestBody Advice advice, HttpServletResponse response){
        OutputStream outputStream = null;
        // 获取文件url
        String fileUrl = advice.getFileUrl();
        // 获取文件后缀
        String suffix = fileUrl.substring(fileUrl.lastIndexOf(".")+1);
        String fileName = "附件."+suffix;
        try {
            InputStream inputStream = OssManagerUtil.downloadFile(fileUrl);
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(b)) != -1) {
                os.write(b, 0, len);
            }
            inputStream.close();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseEntity.SUCCESS("下载成功",null);
    }
}
